<template>
  <div class="user-list">
    <h2>用户列表</h2>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      加载中...
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      {{ error }}
      <button @click="loadUsers">重新加载</button>
    </div>

    <!-- 数据展示 -->
    <div v-else>
      <ul class="user-items">
        <li v-for="user in users" :key="user.id" class="user-item">
          <div class="user-avatar">
            <img v-if="user.avatar" :src="user.avatar" :alt="user.username">
            <span v-else>{{ user.username.charAt(0).toUpperCase() }}</span>
          </div>
          <div class="user-info">
            <h3>{{ user.nickname || user.username }}</h3>
            <p>{{ user.email }}</p>
          </div>
        </li>
      </ul>

      <div v-if="users.length === 0" class="empty">
        暂无用户数据
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 用户列表组件
 * 展示用户数据列表
 */

import { ref, onMounted } from 'vue'
import { userApi } from '@/api/modules/user'
import type { User } from '@/types/user'

// 响应式数据
const users = ref<User[]>([])
const loading = ref<boolean>(false)
const error = ref<string | null>(null)

/**
 * 加载用户列表
 */
const loadUsers = async () => {
  loading.value = true
  error.value = null

  try {
    const response = await userApi.getUserList()
    users.value = response.data.list
  } catch (err: any) {
    error.value = err.message || '加载用户列表失败'
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.loading, .error, .empty {
  text-align: center;
  padding: 40px 20px;
}

.error {
  color: #e53e3e;
}

.user-items {
  list-style: none;
  padding: 0;
  margin: 0;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #cbd5e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  overflow: hidden;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
}

.user-info p {
  margin: 0;
  color: #718096;
  font-size: 14px;
}
</style>
